package cn.bklovezz.yixiantong.ram.service.impl;

import cn.bklovezz.yixiantong.ram.base.ReturnResult;
import cn.bklovezz.yixiantong.ram.util.EncrypyUtil;
import cn.bklovezz.yixiantong.ram.util.UserUtil;
import cn.bklovezz.yixiantong.ram.constant.ResponseMessage;
import cn.bklovezz.yixiantong.ram.constant.StatusCode;
import cn.bklovezz.yixiantong.ram.dto.AdminLoginUser;
import cn.bklovezz.yixiantong.ram.dto.AdminRegisterLoginUser;
import cn.bklovezz.yixiantong.ram.pojo.RefreshInfo;
import cn.bklovezz.yixiantong.ram.entity.LoginUserModel;
import cn.bklovezz.yixiantong.ram.mapper.UserMapper;
import cn.bklovezz.yixiantong.ram.service.AdminUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.UUID;

@Service
@Primary
@Slf4j
public class AdminUserServiceImpl implements AdminUserService {
  @Autowired
  private UserMapper userMapper;

  @Autowired
  private EncrypyUtil encrypyUtil;

  @Autowired
  private UserUtil userUtil;

  @Override
  public ReturnResult<LoginUserModel> register(AdminRegisterLoginUser user) {
    String username = user.getUsername(),
           password = user.getPassword();
    if (!userUtil.getCheckUsernameAndPasswordMessage(user).isEmpty()) {
      throw new RuntimeException(userUtil.getCheckUsernameAndPasswordMessage(user));
    }
    try {
      // 1. 查看一下当前用户是否已经存在
      if (userMapper.findUserByUsername(username) != null) {
        return new ReturnResult<>(
                StatusCode.UserException.getCode(),
                ResponseMessage.UsernameIsExist.getMessage(),
                null
        );
      }
      // 2. 用户的个数不能超过 10 个
      log.info("userMapper.getUserAccountCount() -> {}", userMapper.getUserAccountCount());
      if (userMapper.getUserAccountCount() > 10) {
        return new ReturnResult<>(
                StatusCode.UserException.getCode(),
                ResponseMessage.UserAccountCountExceeded.getMessage(),
                null
        );
      }

      // 3. 添加入库
      user.setPassword(encrypyUtil.encryptMD5(password));
      user.setToken("****");
      user.setExpireTime(null);
      user.setCreateTime(LocalDateTime.now());
      user.setUpdateTime(LocalDateTime.now());
      userMapper.insertUser(user);

      // 4. 返回提示成功
      return new ReturnResult(
              StatusCode.Success.getCode(),
              ResponseMessage.Success.getMessage(),
              user
      );
    } catch (RuntimeException e) {
      return new ReturnResult<>(
              StatusCode.UserException.getCode(),
              ResponseMessage.UnknownError
                      .getMessage()
                      .concat(": ")
                      .concat(e.getMessage()),
              null
      );
    }
  }

  @Override
  public ReturnResult<LoginUserModel> login(AdminLoginUser user) {
    if (!userUtil.getCheckUsernameAndPasswordMessage(user).isEmpty()) {
      throw new RuntimeException(userUtil.getCheckUsernameAndPasswordMessage(user));
    }
    try {
      user.setPassword(encrypyUtil.encryptMD5(user.getPassword()));
      // 1. 检查用户名和密码是否匹配
      LoginUserModel dbUser = userMapper.checkUsernameAndPassword(user);
      if (dbUser == null) {
        return new ReturnResult<>(
                StatusCode.UserException.getCode(),
                ResponseMessage.UsernameOrPasswordError.getMessage(),
                null
        );
      }
      // 2. 更新过期时间 & 令牌
      LocalDateTime currentDateTime = LocalDateTime.now();
      String token = encrypyUtil.encryptMD5(dbUser.getUsername())
              + "-" + encrypyUtil.encryptMD5( currentDateTime.toString())
              + "-"+ encrypyUtil.encryptMD5(UUID.randomUUID().toString());
      dbUser.setToken(token);
      dbUser.setExpireTime(LocalDateTime.now().plusDays(1));
      userMapper.updateUser(dbUser);
      return new ReturnResult<>(
              StatusCode.Success.getCode(),
              ResponseMessage.Success.getMessage(),
              dbUser
      );
    } catch (RuntimeException e) {
      return new ReturnResult<>(
              StatusCode.UserException.getCode(),
              ResponseMessage.UnknownError
                      .getMessage()
                      .concat(": ")
                      .concat(e.getMessage()),
              null
      );
    }
  }

  @Override
  public ReturnResult<Boolean> checkUserStatus(String token) {
    try {
      if (token == null || token.isEmpty()) {
        throw new RuntimeException("token不能为空");
      }

      // 1. 查询用户
      LoginUserModel loginUser = userMapper.findUserByToken(token);

      // 2. 判断用户是否存在
      if (loginUser == null) {
        return new ReturnResult<>(
                StatusCode.NotFound.getCode(),
                ResponseMessage.UserNotFound
                        .getMessage(),
                false
        );
      }
      // 2. 判断用户的 token 过期时间
      if (loginUser.getExpireTime().isBefore(LocalDateTime.now())) {
        return new ReturnResult<>(
                StatusCode.Unauthorized.getCode(),
                ResponseMessage.UserInfoIsInvalid.getMessage(),
                false
        );
      }

      return new ReturnResult<>(
              StatusCode.Success.getCode(),
              ResponseMessage.Success.getMessage(),
              true
      );
    } catch (RuntimeException e) {
      return new ReturnResult<>(
              StatusCode.UserException.getCode(),
              ResponseMessage.UnknownError
                      .getMessage()
                      .concat(": ")
                      .concat(e.getMessage()),
              false
      );
    }
  }

  @Override
  public ReturnResult<RefreshInfo<String>> refreshUserToken(String token) {
    try {
      if (token == null || token.equals("")) {
        throw new RuntimeException("token不能为空");
      }

      // 1. 查询用户
      LoginUserModel loginUser = userMapper.findUserByToken(token);

      // 2. 判断用户是否存在
      if (loginUser == null) {
        return new ReturnResult<>(
                StatusCode.NotFound.getCode(),
                ResponseMessage.UserNotFound
                        .getMessage(),
                null
        );
      }
      // 2. 判断用户的 token 过期时间
      loginUser.setToken(
              encrypyUtil.encryptMD5(LocalDateTime.now() + "-" + UUID.randomUUID())
      );
      loginUser.setExpireTime(LocalDateTime.now().plusDays(1));

      // 3. 更新用户信息
      userMapper.updateUser(loginUser);

      return new ReturnResult<>(
              StatusCode.Success.getCode(),
              ResponseMessage.Success.getMessage(),
              new RefreshInfo<String>(loginUser.getToken(), loginUser.getExpireTime())
      );
    } catch (RuntimeException e) {
      return new ReturnResult<>(
              StatusCode.UserException.getCode(),
              ResponseMessage.UnknownError
                      .getMessage()
                      .concat(": ")
                      .concat(e.getMessage()),
              null
      );
    }
  }

  @Override
  public ReturnResult<Object> deleteUserByUsername(String username) {
    try {
      if (userMapper.findUserByUsername(username) == null) {
        return new ReturnResult<>(
                StatusCode.NotFound.getCode(),
                ResponseMessage.NotFound.getMessage(),
                "用户未找到"
        );
      }

      LoginUserModel loginUserModel = new LoginUserModel();
      loginUserModel.setUsername(username);

      userMapper.deleteUser(loginUserModel);

      return new ReturnResult<>(
              StatusCode.Success.getCode(),
              ResponseMessage.Success.getMessage(),
              ResponseMessage.DeleteSuccess.getMessage()
      );
    } catch (RuntimeException e) {
      return new ReturnResult<>(
              StatusCode.UserException.getCode(),
              ResponseMessage.DeleteFail.getMessage(),
              ResponseMessage.DeleteFail.getMessage() + " : " + e.getMessage()
      );
    }
  }
}
